<template>
  <s-table
    class="h100"
    ref="flowConfigTable"
    :columns="columns"
    :data="loadData"
    :showPagination="true"
    rowKey="key"
    :scrollX="890"
    :row-selection="{
      selectedRowKeys: selectedRowKeys,
      onChange: onSelectChange,
      columnWidth: '60px',
      fixed: true,
    }"
  >
    <template #operation="text">
      <span style="display: flex;">
        <span class="set-margin" style="margin-right: 8px">
          <auth-button @click="edit(text)" :auth="managePerms.dict.update" type="primary" :ghost="true" size="small">
            <i class="iconfont icon-xiugai"/>{{ $t('edit') }}</auth-button>
        </span>
        <span>
          <auth-button @click="deleteTb(text)" :auth="managePerms.dict.delete" type="danger" :ghost="true" size="small">
            <i class="iconfont icon-shanchu3 deleteUlr"/>{{ $t('delete') }}</auth-button>
        </span>
      </span>
    </template>
  </s-table>
</template>
<script>
import { mapState } from 'vuex'
import STable from '@/components/Table/index'
import AuthText from '@/components/AuthText'
import NewEditDict from './NewEditDict'
import { minxinDrawerUse } from '@/utils/mixin'
import { draftTbColumns } from '../config/list'
import { managePerms } from '@/config/permission/index'
import AuthButton from '@/components/AuthButton'
export default {
  mixins: [minxinDrawerUse],
  components: {
    STable,
    AuthText,
    NewEditDict,
    AuthButton
  },
  computed: {
    // 查询参数
    ...mapState({
      queryParams: (state) => state.dict.queryParamsDict
    })
  },
  data () {
    return {
      columns: draftTbColumns,
      managePerms,
      selectedRowKeys: [],
      modelList: [],
      loading: false,
      editRecord: null
    }
  },
  methods: {
    // 请求表格加载数据
    loadData (data = { pageNo: 1, pageSize: 20 }) {
      if (!this.queryParams.dictCode) {
        this.queryParams.dictCode = undefined
        this.$message.info("请选择字典");
        return;
      }      
      return new Promise((resolve, reject) => {
        this.loading = true
        this.$api
          .getDictCodeByKey(this.queryParams.dictCode)
          .then((res) => {
            this.modelList = res.data
            const [index, size, total] = [data.pageNo, data.pageSize, this.modelList.length]
            let len = total / size
            const totalPages = len - parseInt(len) > 0 ? parseInt(len) + 1 : len
            const newProduceNewsData = this.modelList.slice((index - 1) * size, index * size)
            resolve({
              code: '0',
              message: 'success',
              pageNo: index,
              pageSize: size,
              totalCount: total,
              totalPage: totalPages,
              data: [...newProduceNewsData],
            })
          })
          .catch((e) => reject(e))
          .finally(() => {
            this.loading = false
          })
      })
    },
    // 刷新表格
    refreshData(isToFirstPage = true) {
      let obj = null
      if (isToFirstPage) {
        obj = { current: 1 }
      }
      this.$refs.flowConfigTable.loadData(obj)
    },
    // 表格勾选事件
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      let IDS = []
      selectedRows.forEach((item, index) => {
        let obj = item
        IDS.push(obj.id)
      })
      this.$emit('bulkDeletion', IDS)
    },
    // 清空表格勾选项
    emptyTableSelction() {
      this.selectedRowKeys = []
    },
    // 删除字典
    deleteTb(val) {
      const that = this
      that.$confirm({
        title: that.$t('tip'),
        content: that.$t('deleteDictTip'),
        onOk () {
          that.$api.deleteDictCode({ ids: [val.id] }).then(() => {
            that.$message.success(that.$t('successfullyDelete'))
            that.refreshData(false)
            that.emptyTableSelction()
          })
        },
      })
    },
    // 保存编辑
    SaveEditDictData (data) {
      const requestParameters = {
        dictItemId: data.id,
        dictItemName: data.name,
        dictItemRemarks: data.remarks,
        dictItemValue: data.value
      }
      this.$api.editDictCode(requestParameters).then(() => {
        this.$message.success(this.$t('successfullyOperation'))
        this.refreshData(false)
      })
      this.removeRightDrawer()
    },

    // 编辑字典
    edit (recordData = {}) {
      const vm = this
      const buttons = this.getRightDrawerFooterButtons({
        method: 'SaveEditDictData',
        callback () {
          vm.refreshData(false)
        }
      })
      const vars = {
        editRecord: {
          ...recordData,
          dictCode: this.queryParams.dictCode
        }
      }
      vm.showRightDrawer(NewEditDict, vm.$t('edit'), buttons, 'small', vars)
    }
  }
}
</script>
<style scoped></style>
